package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {

    //指定过滤器的类型 "pre","routes","post","error"
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }

    //指定过滤器添加的位置序号(默认有5个过滤器)
    //在默认的第五个过滤器执行完RequestContext中才有serviceId属性
    @Override
    public int filterOrder() {
        return 6;
    }

    //判断针对当前这次请求是否要执行过滤代码
    //如果请求item-service，执行全选判断
    //如果请求user,order，跳过过滤
    @Override
    public boolean shouldFilter() {
        //获得正在调用的服务ID
        //获取正在执行的请求的上下文对象
        RequestContext cxt = RequestContext.getCurrentContext();
        String serviceId = (String) cxt.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase(serviceId);//equalsIgnoreCase忽略大小写
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //http://localhost:3001/item-service/xxxx?token=xxxx
        //得到request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //接收token参数
        String token = request.getParameter("token");
        //如果token参数不存在，则阻止调用，直接返回提示
        if(StringUtils.isBlank(token)){
            //阻止继续访问
            ctx.setSendZuulResponse(false);
            //返回登录提示
            String json=JsonResult.err()
                                  .code(JsonResult.NOT_LOGIN)
                                  .msg("not login...")
                                  .toString();
            ctx.addZuulResponseHeader("Content-Type",
                                      "application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }
        //返回任何数据都无效，现版本是完全无用的返回值
        return null;
    }
}
